import pymysql

from utils.log_util import logger
from utils.read import read_ini

data=read_ini()["mysql"]
db_conf={"host":data["HOST"],
         "port":int(data["PORT"]),
         "user":data["USER"],
         "password":data["PASSWD"],
         "db":data["DB"]}

class MysqlDb:

    #初始化连接
    def __init__(self):
        self.conn=pymysql.connect(**db_conf,autocommit=True)
        self.cur=self.conn.cursor(cursor=pymysql.cursors.DictCursor)
    #查询一条数据
    def select_one(self,sql):
        logger.info(f"执行sql：{sql}")
        self.cur.execute(query=sql)
        result=self.cur.fetchone()
        logger.info(f"sql执行结果：{result}")
        return result

    #查询所有数据
    def select_all(self,sql):
        logger.info(f"执行sql：{sql}")
        self.cur.execute(query=sql)
        result=self.cur.fetchall()
        logger.info(f"sql执行结果：{result}")
        return result

    #执行sql
    def execute_sql(self,sql):
        try:
            logger.info(f"执行sql：{sql}")
            self.cur.execute(sql)
            self.conn.commit()
        except Exception as e:
            logger.info(f"执行sql失败：{sql}")

    #释放资源
    def __del__(self):
        self.cur.close()
        self.conn.close()

db=MysqlDb()

if __name__ == '__main__':
    mysql=MysqlDb()
    # result=mysql.select_one("select code from users_verifycode where mobile='17789617871' order by id desc limit 1")
    result=mysql.select_one("select mobile from users_userprofile  order by id desc limit 1")
    print(result["code"])
